package com.grechur.wanandroidcompose.page

import android.util.Base64
import android.util.Log
import android.widget.Toast
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavHostController
import androidx.navigation.compose.rememberNavController
import com.google.accompanist.pager.ExperimentalPagerApi
import com.google.accompanist.swiperefresh.SwipeRefresh
import com.google.accompanist.swiperefresh.rememberSwipeRefreshState
import com.grechur.wanandroidcompose.bean.article.Article
import com.grechur.wanandroidcompose.bean.banner.BannerItem
import com.grechur.wanandroidcompose.viewmodel.HomeViewModel
import com.grechur.wanandroidcompose.widget.ArticlePage
import com.grechur.wanandroidcompose.widget.BannerView
import com.grechur.wanandroidcompose.widget.OnBottomReached
import com.grechur.wanandroidcompose.widget.banner.BannerPagerView
import kotlinx.coroutines.launch
import java.net.URLEncoder
import java.nio.charset.StandardCharsets

@OptIn(ExperimentalPagerApi::class)
@Composable
fun HomePage(
    homeViewModel: HomeViewModel = viewModel(),
    globalNavHostController: NavHostController,
    modifier: Modifier = Modifier
) {
    DisposableEffect(Unit) {
        Log.e("zhouzhu", "HomePage DisposableEffect")
        onDispose {
            Log.e("zhouzhu", "HomePage onDispose")
        }
    }

    val coroutineScope = rememberCoroutineScope()
    val context = LocalContext.current
    val swipeRefreshState = rememberSwipeRefreshState(isRefreshing = homeViewModel.isRefresh)
    val lazyListState = rememberLazyListState()

    LaunchedEffect(Unit) {
        homeViewModel.getNetBanners()
//        homeViewModel.getHomeArticles()
        Log.e("zhouzhu", "HomePage LaunchedEffect")
    }

    SwipeRefresh(state = swipeRefreshState, onRefresh = {
        coroutineScope.launch {
            homeViewModel.refresh()
        }
    }) {

        lazyListState.OnBottomReached {
            coroutineScope.launch {
                if (!homeViewModel.isRefresh) {
                    homeViewModel.getHomeArticles(homeViewModel.currentPageIndex + 1)
                    Log.e("zhouzhu", "OnBottomReached")
                }
            }
        }

        LazyColumn(
            modifier = Modifier
                .padding(bottom = 56.dp)
                .navigationBarsPadding(),
            state = lazyListState
        ) {
            item {
                homeViewModel.banners.getOrNull().takeIf { !it.isNullOrEmpty() }
                    ?.let { bannerInfos ->
                        val bannerItems = mutableListOf<BannerItem>()
                        bannerInfos.forEach { bannerInfo ->
                            val bannerItem = BannerItem(bannerInfo.imagePath, bannerInfo.url, bannerInfo.title)
                            bannerItems.add(bannerItem)
                        }
                        BannerPagerView(items = bannerItems) {
                            val link = it.url ?: ""
                            val encode = Base64.encodeToString(
                                link.toByteArray(),
                                Base64.NO_WRAP
                            )
                            globalNavHostController.navigate("webView?url=$encode?name=${it.title}")
                        }
                    }
            }

            homeViewModel.homeArticles.let { result: Result<List<Article>> ->
                result.isSuccess.takeIf { it }?.let {
                    result.getOrNull().takeIf { !it.isNullOrEmpty() }
                        ?.let { articles: List<Article> ->
                            itemsIndexed(articles) { index, article ->
                                ArticlePage(globalNavHostController,
                                    article = article,
                                    modifier = Modifier
                                        .padding(horizontal = 10.dp)
                                        .clickable {
                                            Toast
                                                .makeText(
                                                    context,
                                                    "${article.link}",
                                                    Toast.LENGTH_SHORT
                                                )
                                                .show()
                                            val link = article.link ?: ""
                                            val encode = Base64.encodeToString(
                                                link.toByteArray(),
                                                Base64.NO_WRAP
                                            )
                                            globalNavHostController.navigate("webView?url=$encode?name=${article.title}")
                                        },
                                index = index)
                            }
                        }
                } ?: Toast.makeText(
                    context,
                    "${result.exceptionOrNull()?.message}",
                    Toast.LENGTH_SHORT
                ).show()
            }
        }

    }


}

@Preview
@Composable
fun HomePagePreview() {
    HomePage(globalNavHostController = rememberNavController())
}

